package com.mayflygeek.mayflyask.framework.webmvc.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

/**
 * @author 虫虫
 * @team 蜉蝣极客
 * @link www.mayflygeek.com
 * @Emial chongchong@mayflygeek.com
 * 
 */
public class SpringHandlerInterceptor extends HandlerInterceptorAdapter {
	private static final Logger logger = LoggerFactory.getLogger(SpringHandlerInterceptor.class);

	private BeforeAnnotatedMethodHandler beforeAnnotatedMethodHandler = new BeforeAnnotatedMethodHandler();
	private AfterAnnotatedMethodHandler afterAnnotatedMethodHandler = new AfterAnnotatedMethodHandler();

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		beforeAnnotatedMethodHandle(handler, request, response);
		return super.preHandle(request, response, handler);
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		afterAnnotatedMethodHandle(handler, request, response, modelAndView);
		super.postHandle(request, response, handler, modelAndView);
	}

	protected void beforeAnnotatedMethodHandle(Object handler, HttpServletRequest request,
			HttpServletResponse response) {
		try {
			beforeAnnotatedMethodHandler.handler(handler, new Object[] { request, response });
		} catch (Exception e) {
			logger.warn("beforeHandler.handler error", e);
		}
	}

	protected void afterAnnotatedMethodHandle(Object handler, HttpServletRequest request, HttpServletResponse response,
			ModelAndView modelAndView) {
		try {
			afterAnnotatedMethodHandler.handler(handler, new Object[] { request, response, modelAndView });
		} catch (Exception e) {
			logger.warn("afterHandler.handler error", e);
		}
	}

	public void setBeforeAnnotatedMethodHandler(BeforeAnnotatedMethodHandler beforeAnnotatedMethodHandler) {
		this.beforeAnnotatedMethodHandler = beforeAnnotatedMethodHandler;
	}

	public void setAfterAnnotatedMethodHandler(AfterAnnotatedMethodHandler afterAnnotatedMethodHandler) {
		this.afterAnnotatedMethodHandler = afterAnnotatedMethodHandler;
	}
}
